package dao

import (
	"bms/db"
	"bms/model"
	"time"
)

func GetUser(username, password, usertype, phone, email string) *model.User {
	sql := "select * from user where username=? and password=? and usertype=? and phone=? and email=?"
	row := db.Db.QueryRow(sql, username, password, usertype, phone, email)
	user := &model.User{}
	err := row.Scan(&user.Id, &user.Username, &user.Password, &user.Usertype, &user.Phone, &user.Email, &user.CreateTime)
	if err != nil {
		user = &model.User{}
	}
	return user
}

func CheckUser(username string) (*model.User, error) {
	sql := "select id,username,password,usertype,phone,email,create_time from user where username=?"
	row := db.Db.QueryRow(sql, username)
	user := &model.User{}
	err := row.Scan(&user.Id, &user.Username, &user.Password, &user.Usertype, &user.Phone, &user.Email, &user.CreateTime)
	if err != nil {
		user = &model.User{}
	}
	return user, nil
}

func SaveUser(username, password, phone, email string) error {
	sql := "insert into user(username,password,usertype,phone,email,create_time) values (?,?,?,?,?,?)"
	usertype := "普通用户"
	createTime := time.Now().Format("2006-01-02 15:04:05")
	_, err := db.Db.Exec(sql, username, password, usertype, phone, email, createTime)
	if err != nil {
		return err
	}
	return nil
}

func GetAllUser() ([]*model.User, error) {
	sql := "select id,username,password,usertype,phone,email,create_time from user"
	rows, err := db.Db.Query(sql)
	if err != nil {
		return nil, err
	}
	var users []*model.User
	for rows.Next() {
		user := &model.User{}
		rows.Scan(&user.Id, &user.Username, &user.Password, &user.Usertype, &user.Phone, &user.Email, &user.CreateTime)
		users = append(users, user)
	}
	return users, nil
}

func QueryUser(userId int64) bool {
	sql := "select * from user where id=?"
	row := db.Db.QueryRow(sql, userId)
	user := &model.User{}
	row.Scan(&user.Id, &user.Username, &user.Password, &user.Usertype, &user.Phone, &user.Email, &user.CreateTime)
	if user != nil {
		return true
	}
	return false
}

func ReviseUser(user *model.User) error {
	sql := "update user set password=?,create_time=? where id=?"
	_, err := db.Db.Exec(sql, user.Password, user.CreateTime, user.Id)
	if err != nil {
		return err
	}
	return nil
}

func DeleteUser(userId int64) error {
	//首先要删除borrow_items里面的数据
	borrow, err := GetBorrowByUserId(userId)
	if err != nil {
		borrow = &model.Borrow{}
	}
	sql2 := "delete from borrow_items where borrow_id=?"
	db.Db.Exec(sql2, borrow.BorrowId)
	//删除外键约束的userId
	sql1 := "delete from borrows where user_id=?"
	db.Db.Exec(sql1, userId)
	//删除user
	sql := "delete from user where id=?"
	db.Db.Exec(sql, userId)
	return nil
}
